import {
  JsonWriterReturns,
  xlsxWriter,
  XlsxWriterReturns,
  jsonWriter,
  cpus,
} from "./index.js";
import { reactive, computed, ComputedRef } from "vue";
import { CsvLine } from "./csv-accumulator";
export interface XlsxProgress extends XlsxWriterReturns {
  occupied: number;
}
export interface JsonProgress extends JsonWriterReturns {
  occupied: number;
}
export class WriterWorker {
  leastOccupied: ComputedRef<number>;
  progressArr: (XlsxProgress | JsonProgress)[];
  write: (
    /**
     * 要写入的数据
     */
    data: CsvLine[] | any,
    /**
     * 路径
     */
    path: string
  ) => Promise<true>;

  constructor(use: "xlsx" | "json", workerThreads: number = cpus()) {
    this.progressArr = reactive(
      Array.from({ length: workerThreads })
        .map(() => (use === "xlsx" ? xlsxWriter() : jsonWriter()))
        .map((e) => {
          return { ...e, occupied: 0 };
        })
    );
    this.leastOccupied = computed(() => {
      let i: number = 0;
      let maxOccupied: number = 0;
      let pgAr = this.progressArr;
      for (let i0 in pgAr) {
        if (pgAr[i0].occupied > maxOccupied) {
          maxOccupied = pgAr[i0].occupied;
          i = +i0;
        }
      }
      return i;
    });
    let writerLeastOccupied: ComputedRef<XlsxProgress | JsonProgress> =
      computed(() => this.progressArr[this.leastOccupied.value]);
    this.write = async (...args) => {
      let currentProgress = writerLeastOccupied.value;
      currentProgress.occupied++;
      let _result = await writerLeastOccupied.value.write(...args);
      currentProgress.occupied--;
      return _result;
    };
  }
  kill() {
    this.progressArr.forEach((e) => e.kill());
    for (let key in this) {
      // @ts-expect-error
      this[key] = null;
    }
  }
}
